package cn.edu.scau.cmi.wangmaoren.comprehension.dao;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.edu.scau.cmi.wangmaoren.comprehension.domain.Student;
import cn.edu.scau.cmi.wangmaoren.comprehension.util.HibernateFactory;

public class StudentDAO
{
	private static final Logger log = LoggerFactory.getLogger(StudentDAO.class);
	public static final String NAME = "name";
	private Session session;

	public Session getSession()
	{
		session = HibernateFactory.getSession();
		return session;
	}

	public void save(Student transientInstance)
	{
		try
		{
			getSession();
			Transaction transaction = session.beginTransaction();
			session.save(transientInstance);
			transaction.commit();
		} catch (RuntimeException re)
		{
			throw re;
		}
	}

	public void delete(Student persistentInstance)
	{
		log.debug("deleting Student instance");
		try
		{
			getSession();
			Transaction transaction = session.beginTransaction();
			session.delete(persistentInstance);
			log.debug("delete successful");
			transaction.commit();
		} catch (RuntimeException re)
		{
			log.error("delete failed", re);
			throw re;
		}
	}

	public void update(Student transientInstance)
	{
		log.debug("updating Student instance");
		try
		{
			getSession();
			Transaction transaction = session.beginTransaction();
			session.update(transientInstance);
			log.debug("update successful");
			transaction.commit();
		} catch (Exception e)
		{
			log.error("update failed", e);
			throw e;
		}
	}

	public Student findById(long id)
	{
		log.debug("getting Student instance with id: " + id);
		try
		{
			Student instance = (Student) getSession().get(Student.class, id);
			return instance;
		} catch (RuntimeException re)
		{
			log.error("get failed", re);
			throw re;
		}
	}

	public List<Student> findAll()
	{
		log.debug("finding all Student instances");
		try
		{
			String queryString = "from Student";
			Query queryObject = getSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re)
		{
			log.error("find all failed", re);
			throw re;
		}
	}

	public void attachDirty(Student instance)
	{
		log.debug("attaching dirty Student instance");
		try
		{
			getSession();
			Transaction transaction = session.beginTransaction();
			session.saveOrUpdate(instance);
			log.debug("attach successful");
			transaction.commit();
		} catch (RuntimeException re)
		{
			log.error("attach failed", re);
			throw re;
		}
	}
}
